<template>
	<view class="container">
		<u-navbar :custom-back="back" title="小程序登录"></u-navbar>
		<view class="wx-auth-container">
			<div class="box">
				<view class="logo-info">
					<text class="title">欢迎进入{{ projectName }}</text>
				</view>
				<view class="small-tips">
					<view>为了更好的为您提供优质服务,{{ projectName }}需要您</view>
					<view>授权手机号登录</view>
				</view>
				<view class="btns">
          <button v-if="checked" type="primary" class="btn-auth"  open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
            手机号授权登录
          </button>
          <button v-else type="primary" class="btn-auth"  @click="phoneClick" >
            手机号授权登录
          </button>
					<div @click="backToHome" class="btn-callback">暂不登录</div>
				</view>
				<div class="privacy">
            <u-checkbox shape="circle" v-model="checked" :active-color="lightColor">
              <div class="flex">
                阅读并同意<navigator class="light-color" url="/pages/mine/agree?type=PRIVACY_POLICY&title=隐私协议">《隐私协议》</navigator>
                <navigator class="light-color" url="/pages/mine/agree?type=USER_AGREEMENT&title=用户协议">《用户协议》</navigator>
              </div>
            </u-checkbox>
        </div>
			</div>
		</view>
	</view>
</template>

<script>


	import {
		getUserInfo
	} from "@/api/members";
  import clStorage from "@/utils/storage.js"; //缓存
	import config from '@/config/config'
	export default {
		data() {
			return {
				lightColor:this.$lightColor,
				checked:false,
        configs:config,
				// 是否展示手机号码授权弹窗，默认第一步不展示，要先获取用户基础信息
				phoneAuthPopup: false,
				// 授权信息展示，商城名称
				projectName: config.name,
				//微信返回信息，用于揭秘信息，获取sessionkey
				code: "",
				//微信昵称
				nickName: "",
        logingFlag: false,
				//微信头像
				image: "",
			};
		},

		//微信小程序进入页面，先获取code，否则几率出现code和后续交互数据不对应情况
		mounted() {
			// 小程序默认分享
			uni.showShareMenu({
				withShareTicket: true
			});


      //获取code
      uni.login({
        success: (res) => {
          if(res.errMsg === "login:ok") {
            this.code = res.code
          } else {
            uni.showToast({
              title: "系统异常，请联系管理员！"
            })
          }
        },
      });

		},
		methods: {
			/**
			 * 小程序返回bug
			 * 1.介于微信登录是在login.vue的基础上作为判断跳转来
			 * 所以在页面栈中会自动记录回退路径，所以导致每次微信小程序点击回退就会自动返回login页面
			 * 当然login页面的判断就是 没有登录就会跳转到微信小程序页面 导致了无法回退到之前页面
			 * 2.解决方法： 尝试在回退的时候判断地址，让回退多一级这样就避免了
			 */

			back() {
				this.$utils.whetherNavigate("wx");
			},
			backToHome() {
				uni.switchTab({
					url: `/pages/tabbar/home/index`,
				});
			},

      phoneClick(){
        if(!this.checked){
          this.$utils.toast('请阅读并同意相关协议');
          return
        }
      },
			//获取手机号授权
			getPhoneNumber(e) {
        if(!this.checked){
          this.$utils.toast('请阅读并同意相关协议');
          return
        }else{
          let mobileAuthCode = e.detail.code;
          let _this = this;
          uni.login({
            provider: 'weixin',
            success: function(loginRes) {
              let code = loginRes.code;
              if (mobileAuthCode){
                _this.$clApi.login
                    .wxXCXMobileAuthLogin({
                      data: {
                        code: code,
                        mobileAuthCode: mobileAuthCode,
                      },
                    })
                    .then(res => {
                      if (res.data && res.data.loginFlag) {
                        this.getUserInfoMethods(res);
                        uni.navigateBack({
                          delta: 1,
                        });
                      } else {
                        _this.$utils.toast(res.data.errMsg);
                      }
                    });
              }else{
                _this.$utils.toast('微信授权失败，请稍后重试');
              }
            },
            fail: e => {
              console.log(e);
              _this.$utils.toast('微信授权失败，请稍后重试');
            },
          });
        }

			},

      // 登录成功之后获取用户信息
      getUserInfoMethods(res) {
        clStorage.setAccessToken(res.data.token);
        clStorage.setRefreshToken(res.data.refreshToken);

        /**
         * 登录成功后获取个人信息
         */
        this.$clApi.member.loadMemberInfo().then((user) => {
          /**
           * 个人信息存储到缓存userInfo中
           */
          clStorage.setUserInfo(user.data);
          clStorage.setHasLogin(true);
          clStorage.setAutoCp(0)
          // 登录成功
          uni.showToast({
            title:"提示",
            content: "登录成功!",
            icon: "none",
          });


          this.$utils.whetherNavigate();
        });

      },
		},
	};
</script>
<style lang="scss" scoped>
	/*微信授权*/
	page {
		background-color: #ffffff;
	}

	.wx-auth-container {
		width: 100%;
		margin-top: 20%;
	}

	.logo-info {
		display: flex;
		flex-wrap: nowrap;
		justify-content: flex-start;
		flex-direction: row;
		align-items: flex-start;
		padding: 20rpx;

		flex-direction: column;
		font-weight: bold;
	}

	image {
		width: 100px;
		height: 100px;
		text-align: center;
		-webkit-transform: scale(2.5);
		transform: scale(2.5);
	}

	.logo-info-img {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		border: none;
	}

	text.title,
	text.shop {
		display: inline-block;
		font-size: 60rpx;
		color: #333;
	}

	text.shop {
		display: inline-block;
		font-size: 55rpx;
		color: #333;
	}

	.box {
		margin: 0 32rpx;
	}

	/* 文字提示*/
	.small-tips {
		width: 94%;
		padding: 20rpx;
		font-size: 24rpx;
		margin: 0 0 20rpx;
		color: #999;
	}

	.auth-button {
		padding: 10px 20px;
		width: calc(100% - 20 * 4rpx);
	}

	.tips {
		width: 80%;
		text-align: left;
		margin: 6% 10%;
		margin-top: 48rpx;
		line-height: 1.75;
	}

	.register {
		color: $weChat-color !important;
		border: none !important;
		background: #fff !important;
	}

.btn-auth {
  width: 92%;
  margin: 0 auto 40rpx;
  border-radius: 100px;
}
.btn-callback {
  text-align: center;
  font-size: 30rpx;
  background: #ededed;
  height: 90rpx;
  line-height: 90rpx;
  border-radius: 100px;
  width: 92%;
  margin: 0 auto;
}

	.btn-callback {
		text-align: center;
		font-size: 30rpx;
		background: #ededed;
		height: 90rpx;
		line-height: 90rpx;
		border-radius: 100px;
		width: 92%;
		margin: 0 auto;
	}

	.btns {
		margin-top: 100rpx;
		display: flex;
		flex-direction: column;
		width: 100%;
		justify-content: center;
	}

	@keyframes mymove {
		0% {
			transform: scale(1);
			/*开始为原始大小*/
		}

		25% {
			transform: scale(1.1);
			/*放大1.1倍*/
		}

		50% {
			transform: scale(1);
		}

		75% {
			transform: scale(1.1);
		}
	}

.privacy{
  text-align: center;
  margin-top: 20rpx;
  width: 100%;
}
</style>
